package com.kyzh.core.pager.weal

import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.gushenge.atools.util.AView
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.Nav
import com.gushenge.core.beans.WealBean
import com.gushenge.core.beans.WealDoing
import com.gushenge.core.dao.GlobalConsts
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.requests.WealRequest
import com.kyzh.core.R
import com.kyzh.core.activities.AnswerActivity
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.activities.TaskCenterActivity
import com.kyzh.core.adapters.NavAdapter
import com.kyzh.core.databinding.FragmentWealV3Binding
import com.kyzh.core.databinding.ItemWealTopBinding
import com.kyzh.core.databinding.TablayoutWealTextBinding
import com.kyzh.core.pager.weal.accountbuy.AccountBuyFragment
import com.kyzh.core.pager.weal.dailytask.DailyTaskFragment
import com.kyzh.core.pager.weal.growth.GrowthFragment
import com.kyzh.core.pager.weal.huodong.HuoDongFragment
import com.kyzh.core.pager.weal.recover.RecoverActivity
import com.kyzh.core.utils.*
import com.makeramen.roundedimageview.RoundedImageView
import org.jetbrains.anko.backgroundColorResource
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.textColorResource


class WealFragment : BaseFragment() {


    private lateinit var db:FragmentWealV3Binding
    private val topAdapter = TopAdapter()
    private val contentAdapter = NavAdapter(R.layout.item_frag_weal_function, mutableListOf())
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        db =  FragmentWealV3Binding.inflate(inflater)
        return db.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
        initData()
    }

    private fun initData() {
        val layoutParams: ViewGroup.LayoutParams = db.appbar.getLayoutParams()
        val behavior = (layoutParams as CoordinatorLayout.LayoutParams).behavior
        if (behavior is AppBarLayout.Behavior) {
            behavior.topAndBottomOffset =0
        }
        WealRequest.getWeal{
            this?.apply {
                if(topdata!=null&&topdata.size>4){
                    val take = this.topdata.take(3)
                    topAdapter.setNewInstance(take.toMutableList())
                }else{
                    topAdapter.setNewInstance(this.topdata)
                }
                contentAdapter.setNewInstance(this.maindata)
                initTab(renwu)
            }
        }
    }
    fun initTab(renwu :ArrayList<WealBean.Renwu>){
        val beans = arrayListOf<Fragment>(
            DailyTaskFragment(),
            GrowthFragment(), HuoDongFragment()
        )

       if(renwu.size>3){
           beans.add( AccountBuyFragment())
       }



        db. viewpager.init(this,beans)
        val mediator  = TabLayoutMediator(db.tab, db. viewpager) { tab, position -> //这里可以自定义TabView
            tab.text = renwu[position].title
            val inflate = DataBindingUtil.inflate<TablayoutWealTextBinding>(
                LayoutInflater.from(requireContext()),
                R.layout.tablayout_weal_text,
                null,
                false
            )
            inflate.tv.text= tab.text
            tab.customView = inflate.root
        }
        db. appbar.addOnOffsetChangedListener(object : ViewUtils.AppBarLayoutStateChangeListener() {
            override fun onStateChanged(appBarLayout: AppBarLayout, state: State) {
                when (state) {
                    State.EXPANDED -> {
                        AView.setStatusBar(requireActivity(), false)
                        db. tvTitle.textColorResource =R.color.white
                        db. tvTitle.text = "福利"
                    }

                    State.COLLAPSED -> {
                        AView.setStatusBar(requireActivity(), true)
                        db. tvTitle.textColorResource = R.color.font_33
                        db. tvTitle.text = "福利"
                    }
                    State.INTERMEDIATE -> {
                        AView.setStatusBar(requireActivity(), true)
                        db. tvTitle.textColorResource = R.color.font_33
                        db. tvTitle.text = ""
                        db. toolbar.backgroundColorResource = android.R.color.transparent

                    }
                }
            }
        })
        db.tab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                tab.customView = null
                val inflate = DataBindingUtil.inflate<TablayoutWealTextBinding>(
                    LayoutInflater.from(requireContext()),
                    R.layout.tablayout_weal_text,
                    null,
                    false
                )
                inflate.tv.textSize = 18f
                inflate.view.setVisibility(true)
                inflate.tv.text= tab.text
                inflate.tv.typeface = Typeface.DEFAULT_BOLD;
                tab.customView = inflate.root
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                tab.customView = null
                val inflate = DataBindingUtil.inflate<TablayoutWealTextBinding>(
                    LayoutInflater.from(requireContext()),
                    R.layout.tablayout_weal_text,
                    null,
                    false
                )

                inflate.tv.text= tab.text
                inflate.tv.textSize = 14f
                inflate.view.visibility = View.INVISIBLE
                tab.customView = inflate.root
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                tab.customView = null
                val inflate = DataBindingUtil.inflate<TablayoutWealTextBinding>(
                    LayoutInflater.from(requireContext()),
                    R.layout.tablayout_weal_text,
                    null,
                    false
                )
                inflate.tv.textSize = 18f
                inflate.tv.typeface = Typeface.DEFAULT_BOLD;
                inflate.view.setVisibility(true)
                inflate.tv.text= tab.text
                tab.customView = inflate.root
            }
        })
        mediator.attach()
    }
    private var moveY = 0
    private fun initView() {
        AView.setMargins(db.toolbar,0,AView.getStatusBarHeight(requireActivity()),0,0)
        AView.setMargins(db.topbg,0,AView.getStatusBarHeight(requireActivity())+dip(45),0,0)
        db.revTop.layoutManager = object :GridLayoutManager(requireContext(),3){
            override fun canScrollHorizontally()=  false
            override fun canScrollVertically()  = false
        }
        db.revTop.adapter = topAdapter
        db.revContent.layoutManager = object :GridLayoutManager(requireContext(),4){
            override fun canScrollHorizontally()=  false
            override fun canScrollVertically()  = false
        }
        db.revContent.adapter = contentAdapter
        db.appbar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
                Log.e("TAG", "onOffsetChanged: "+verticalOffset   +"--"+appBarLayout?.y )
                moveY = verticalOffset
            }

        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        initData()
    }

    override fun onResume() {
        super.onResume()
    }
    private inner class TopAdapter():BaseQuickAdapter<Nav,BaseDataBindingHolder<ItemWealTopBinding>>(R.layout.item_weal_top){
        override fun convert(holder: BaseDataBindingHolder<ItemWealTopBinding>, item: Nav) {
            holder.dataBinding?.data = item
            holder.dataBinding?.root?.setOnClickListener {
                context.navClickByLogin(item)
            }
        }
    }
    private inner class Adapter(beans:ArrayList<WealDoing>):BaseMultiItemQuickAdapter<WealDoing, BaseViewHolder>(beans){
        init {
            addItemType(0,R.layout.item_weal0)
            addItemType(1,R.layout.item_weal1)
            addItemType(2,R.layout.item_weal2)
            addItemType(3,R.layout.item_weal3)
        }
        override fun convert(holder: BaseViewHolder, item: WealDoing) {
            when(holder.itemViewType){
                0->{
                    val tvTask = holder.getView<TextView>(R.id.tvTask)
                    val tvPointMall = holder.getView<TextView>(R.id.tvPointMall)
                    val tvDeal = holder.getView<TextView>(R.id.tvDeal)
                    val rev = holder.getView<RecyclerView>(R.id.rev)
                    if(item.nav.isNullOrEmpty() ){
                        tvTask.setVisibility(true)
                        tvPointMall.setVisibility(true)
                        tvDeal.setVisibility(true)
                        rev.setVisibility(false)
                        tvTask.setVisibility(false)
                        tvPointMall.setVisibility(false)
                        tvDeal.setVisibility(false)
                        rev.setVisibility(true)
                        tvTask.setOnClickListener {
                            if (startLogin()){
                                AnswerActivity.start(context)
                            }
                        }
                        tvPointMall.setOnClickListener {
                            if (startLogin()){
                                RecoverActivity.start(context)
                            }
                        }
                        tvDeal.setOnClickListener {
                            if (startLogin()){
                                startActivity<TaskCenterActivity>()
                            }
                        }
                    }else{
                        tvTask.setVisibility(false)
                        tvPointMall.setVisibility(false)
                        tvDeal.setVisibility(false)
                        rev.setVisibility(true)
                        var list :MutableList<Nav> = mutableListOf()
                        list = if(item.nav.size > 3){
                            item.nav.subList(0,3)
                        }else{
                            item.nav.toMutableList()
                        }
                        rev.layoutManager = GridLayoutManager(requireContext(),list.size)
                        rev.adapter = object :BaseQuickAdapter<Nav,BaseDataBindingHolder<ItemWealTopBinding>>(R.layout.item_weal_top,list){
                            override fun convert(
                                holder: BaseDataBindingHolder<ItemWealTopBinding>,
                                item: Nav
                            ) {
                                holder.dataBinding?.data = item
                                holder.itemView.setOnClickListener {
                                    if (item.login==1){
                                        if (context.startLogin()){
                                            context.navClickByLogin(item)
                                        }
                                    }else{
                                        context.navClickByLogin(item)
                                    }
                                }
                            }

                        }
                    }

                }
                1->{
                    val rvWealFun = holder.getView<RecyclerView>(R.id.rvWealFun)

                    rvWealFun.layoutManager = object : GridLayoutManager(requireContext(), 4){
                        override fun canScrollHorizontally(): Boolean {
                            return false
                        }

                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rvWealFun.adapter = NavAdapter(R.layout.item_frag_me_function, item.nav)
                }
                3->{
                    holder.setText(R.id.tvTitle,item.title)
                            .setText(R.id.tvTime,"${getString(R.string.addedTime)}: ${item.time}")
                    holder.getView<RoundedImageView>(R.id.ivImage).loadImage(requireActivity(),item.image)
                    holder.itemView.setOnClickListener {
                        startActivity<BrowserActivity>(GlobalKeys.TITLE to item.title, GlobalKeys.LINK to GlobalConsts.NEWS_XQ + item.id)
                    }
                }
            }
        }
    }
}